/**
 *  Copyright (C) 2008-2013  Telosys project org. ( http://www.telosys.org/ )
 *
 *  Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *          http://www.gnu.org/licenses/lgpl.html
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.telosys.persistence.syntax;

import java.util.HashMap;
import java.util.List;

import org.telosys.persistence.TelosysPersistenceException;

public class StatementTranslator 
{
    private HashMap<String,String> _fieldsToColumns = null ;

	public StatementTranslator(HashMap<String, String> fieldsToColumns) {
		super();
		this._fieldsToColumns = fieldsToColumns;
	}

	public String fieldNameToColumnName( String fieldName ) 
	{
		if ( _fieldsToColumns != null ) 
		{
			if ( fieldName.charAt(0) == '$' ) 
			{
				//--- It must be a field name
				String realFieldName = fieldName.substring(1);
				String columnName = _fieldsToColumns.get(realFieldName);
				if ( columnName != null ) {
					return columnName ;
				}
				else {
					//--- This field name is unknown => it's an error
					throw new TelosysPersistenceException("Unknown field '" + realFieldName + "', cannot get column name");
				}
			}
			else
			{
				//--- It can be a field name or a SQL key word
				String columnName = _fieldsToColumns.get(fieldName);
				if ( columnName != null ) {
					return columnName ;
				}
				else {
					return fieldName ; // Keep the original word
				}
			}
		}
		else {
			throw new TelosysPersistenceException("Fields to columns mapping is null in StatementTranslator");
		}
	}
	
	public String toSQL(String objectRequestFragment ) 
	{
		if ( null == objectRequestFragment ) {
			return null ;
		}
		
		StatementTokenizer  sqlTokenizer = new StatementTokenizer();
		List<StatementPart> parts = sqlTokenizer.getParts(objectRequestFragment); 
		StringBuffer sb = new StringBuffer();
		for ( StatementPart p : parts ) 
		{
			if ( p.isWord() && ( ! p.isReservedWord() ) )
			{
				String colName = fieldNameToColumnName( p.getPart() ) ;
				sb.append(colName) ;
			}
			else
			{
				sb.append(p.getPart()) ;
			}
		}
		return sb.toString();
	}
	
}
